package com.cloudkinto.service.orderback.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.common.BeanConvert;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.common.CodeGenerator;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.utils.OrderCodeUtil;
import com.cloudkinto.common.utils.StringsUtil;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.dao.DicBusinessItemDao;
import com.cloudkinto.entity.*;
import com.cloudkinto.dao.FbaOrderBackDao;
import com.cloudkinto.service.company.CompanyService;
import com.cloudkinto.service.dic.DicBusinessItemService;
import com.cloudkinto.service.orderback.FbaOrderBackProductService;
import com.cloudkinto.service.orderback.FbaOrderBackService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.orderback.vo.*;
import com.cloudkinto.service.storage.FbaStorageService;
import com.cloudkinto.service.storage.StorageService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author ding
 * @since 2023-08-02
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class FbaOrderBackServiceImpl extends ServiceImpl<FbaOrderBackDao, FbaOrderBackDo> implements FbaOrderBackService {
    @Autowired
    private FbaOrderBackDao dao;
    @Autowired
    private StorageService storageService;
    @Autowired
    private FbaOrderBackProductService fbaBackProductService;
    @Autowired
    private DicBusinessItemService dicItemDao;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private FbaOrderBackProductService itemService;

    @Override
    public SingleResult addInit() {
        Map map = new HashMap();
        map.put("storage", storageService.getStorageList());
        map.put("company", companyService.getInitList(null));
        return SingleResult.success(map);
    }

    @Override
    public Object add(FbaOrderBackAddReq req, Long userId) {
        FbaOrderBackDo entityDo = new FbaOrderBackDo();
        BeanUtils.copyProperties(req, entityDo);
        handlerAddBefore(entityDo, userId);
        entityDo.setStatus(DicBusinessItemConstant.fbaOrderBackCreate);
        entityDo.setOrderNumber(OrderCodeUtil.getFbaBackOrderNumber(entityDo.getId()));
        dao.insert(entityDo);
        itemService.saveItems(entityDo.getId(), req.getItems(), entityDo.getCreateBy());

        return handlerAddAfter(entityDo);
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(FbaOrderBackDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(FbaOrderBackDo entityDo) {
//        Object res = new Object();
//        BeanUtils.copyProperties(entityDo, res);
        return entityDo;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success(detail(id));
    }

    @Override
    public Object update(FbaOrderBackUpdateReq req, Long userId) {
        /*FbaOrderBackDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return handlerUpdateAfter(entityDo);*/
        return null;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(FbaOrderBackDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(FbaOrderBackDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        FbaOrderBackDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(FbaOrderBackDo entityDo, Long userId) {
        entityDo.setDeleteBy(userId);
        entityDo.setDeleteTime(new Date());
    }

    @Override
    public FbaOrderBackDetailRes detail(Long id) {
        FbaOrderBackDo entityDo = dao.selectById(id);
        FbaOrderBackDetailRes res = new FbaOrderBackDetailRes();
        BeanUtils.copyProperties(entityDo, res);
        return handlerDetailAfter(res);
    }

    //查询明细之后要执行的业务定制处理
    private FbaOrderBackDetailRes handlerDetailAfter(FbaOrderBackDetailRes res) {
        CompanyDo byId = companyService.getById(res.getCompanyId());
        if (byId != null)
            res.setCompanyCode(byId.getCompanyCode());

        StorageDo storageDo = storageService.getById(res.getStorageId());
        if (storageDo != null)
            res.setStorageName(storageDo.getStorageName());
        res.setItems(fbaBackProductService.getItemListByOrderId(res.getId()));
        return res;
    }

    @Override
    public SingleResult pageInit() {
        Map map = new HashMap();
        map.put("storage", storageService.getStorageList());
        map.put("company", companyService.getInitList(null));
        return SingleResult.success(map);
    }

    @Override
    public List<FbaOrderBackPageRes> getList(Map<String, String> map) {
        QueryWrapper<FbaOrderBackDo> wrapper = queryBuild(map);
        List<FbaOrderBackDo> list = this.list(wrapper);
        List<FbaOrderBackPageRes> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<FbaOrderBackDo> wrapper = queryBuild(map);
        IPage<FbaOrderBackDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<FbaOrderBackPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        result.setMapInfo(countStatus(map));
        return result;
    }

    private Map countStatus(Map<String, String> map) {
        List<Map> result = new ArrayList<>();
        map.put("status", "");

        Map mapTotal = new HashMap();
        List<FbaOrderBackDo> list = this.list(queryBuild(map));
        mapTotal.put("count", list.size());
        mapTotal.put("id", "");
        mapTotal.put("name", StringsUtil.createI18Message("全部"));
        result.add(mapTotal);

        Map<Long, List<FbaOrderBackDo>> listMap = list.stream().collect(Collectors.groupingBy(FbaOrderBackDo::getStatus));
        LambdaQueryWrapper<DicBusinessItemDo> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.fbaOrderBack);
        wrapper1.orderByAsc(DicBusinessItemDo::getSort);
        for (DicBusinessItemDo itemDo : dicItemDao.list(wrapper1)) {
            Map map1 = new HashMap();
            map1.put("id", itemDo.getId());
            if (listMap.get(itemDo.getId()) != null) {
                map1.put("count", listMap.get(itemDo.getId()).size());
            } else {
                map1.put("count", 0);
            }
            map1.put("name", StringsUtil.createI18Message(itemDo.getDicItemValue()));
            result.add(map1);
        }


        Map map2 = new HashMap();
        map2.put("census", result);
        return map2;
    }

    //查询分页列表之后对列表数据的处理
    private List<FbaOrderBackPageRes> handlerListAfter(List<FbaOrderBackDo> list) {
        return list.stream().map(new Function<FbaOrderBackDo, FbaOrderBackPageRes>() {
            @Override
            public FbaOrderBackPageRes apply(FbaOrderBackDo fbaOrderBackDo) {
                FbaOrderBackPageRes res = BeanConvert.INSTANCE.fbaBackOrderVo(fbaOrderBackDo);
                CompanyDo byId = companyService.getById(fbaOrderBackDo.getCompanyId());
                if (byId != null)
                    res.setCompanyCode(byId.getCompanyCode());

                StorageDo storageDo = storageService.getById(fbaOrderBackDo.getStorageId());
                if (storageDo != null)
                    res.setStorageName(storageDo.getStorageName());
                List<FbaOrderBackProductDo> productDoList = fbaBackProductService.getBaseMapper().selectList(new LambdaQueryWrapper<FbaOrderBackProductDo>()
                        .eq(FbaOrderBackProductDo::getOrderId, fbaOrderBackDo.getId()));
                if (productDoList != null && productDoList.size() > 0) {
                    int totalCount = 0;
                    int skuCount = 0;
                    Long lasSku = 0L;
                    for (FbaOrderBackProductDo fbaOrderBackProductDo : productDoList) {
                        totalCount = totalCount + fbaOrderBackProductDo.getCount();
                        if (!lasSku.equals(fbaOrderBackProductDo.getProductId())) {
                            skuCount++;
                        }
                        lasSku = fbaOrderBackProductDo.getProductId();
                    }

                    res.setTotalCount(totalCount);
                    res.setSkuCount(skuCount);
                }
                return res;
            }
        }).collect(Collectors.toList());
    }

    private IPage<FbaOrderBackDo> pageInit(Map<String, String> map) {
        IPage<FbaOrderBackDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<FbaOrderBackDo> queryBuild(Map<String, String> map) {
        QueryWrapper<FbaOrderBackDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("order_number", map.get("keyword")).or();
            wrapper.like("amazon_order_id", map.get("keyword")).or();
            wrapper.like("track_number", map.get("keyword")).or();
        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            wrapper.eq("status", map.get("status"));
        }
        if (StringUtils.isNotBlank(map.get("storageId"))) {
            wrapper.eq("storage_id", map.get("storageId"));
        }
        if (StringUtils.isNotBlank(map.get("companyId"))) {
            wrapper.eq("company_id", map.get("companyId"));
        }
        if (StringUtils.isNotBlank(map.get("storageId"))) {
            wrapper.eq("storage_id", map.get("storageId"));
        }
        if (StringUtils.isNotBlank(map.get("startDate"))) {
            if ("2".equals(map.get("dateType"))) {
                wrapper.ge("input_time", map.get("startDate"));
            } else {
                wrapper.ge("create_time", map.get("startDate"));
            }
        }
        if (StringUtils.isNotBlank(map.get("endDate"))) {
            if ("2".equals(map.get("dateType"))) {
                wrapper.lt("input_time", TimeUtils.addDaysFormat(map.get("endDate"), "yyyy-MM-dd", 1));
            } else {
                wrapper.lt("create_time", TimeUtils.addDaysFormat(map.get("endDate"), "yyyy-MM-dd", 1));
            }
        }
        return wrapper.orderByDesc("create_time");
    }


}
